package com.weichen.studentgameexchange.game.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.weichen.studentgameexchange.game.common.Result;
import com.weichen.studentgameexchange.game.dao.UserGameCollectionMapper;
import com.weichen.studentgameexchange.game.entity.Game;
import com.weichen.studentgameexchange.game.entity.UserGameCollection;
import com.weichen.studentgameexchange.game.entity.vo.CollectionVo;
import com.weichen.studentgameexchange.game.entity.vo.GameVo;
import com.weichen.studentgameexchange.game.feign.MemberFeignClient;
import com.weichen.studentgameexchange.game.service.IUserGameCollectionService;
import com.weichen.studentgameexchange.member.entity.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 惟尘
 * @since 2025-02-01
 */
@Service
public class UserGameCollectionServiceImpl extends ServiceImpl<UserGameCollectionMapper, UserGameCollection> implements IUserGameCollectionService {

    @Autowired
    UserGameCollectionMapper userGameCollectionMapper;
    @Autowired
    MemberFeignClient memberFeignClient;

    @Override
    public Page<CollectionVo> adminPage(Integer page, Integer size) {
        Page<UserGameCollection> collectionPage = new Page<>(page, size);
        LambdaQueryWrapper<UserGameCollection> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(UserGameCollection::getCollectionId);
        Page<UserGameCollection> selectPage = userGameCollectionMapper.selectPage(collectionPage, lambdaQueryWrapper);
        List<UserGameCollection> records = selectPage.getRecords();

        // 对 gameIds 和 userIds 进行去重处理
        List<Long> gameIds = records.stream()
                .map(UserGameCollection::getGameId)
                .distinct()
                .toList();
        List<Long> userIds = records.stream()
                .map(UserGameCollection::getUserId)
                .distinct()
                .toList();

        // 批量查询游戏信息并构建映射（去重后无重复键）
        Map<Long, String> gameNameMap = new HashMap<>();
        if (!gameIds.isEmpty()) {
            gameNameMap = Db.lambdaQuery(Game.class)
                    .in(Game::getGameId, gameIds)
                    .list()
                    .stream()
                    .collect(Collectors.toMap(Game::getGameId, Game::getGameName));
        }

        // 批量查询用户信息并构建映射（去重后无重复键）
        Map<Long, String> userNameMap = new HashMap<>();
        if (!userIds.isEmpty()) {
            List<User> users = memberFeignClient.getUsersByIds(userIds);
            userNameMap = users.stream()
                    .collect(Collectors.toMap(User::getUserId, User::getUsername));
        }

        // 转换VO并填充关联信息
        Map<Long, String> finalGameNameMap = gameNameMap;
        Map<Long, String> finalUserNameMap = userNameMap;
        List<CollectionVo> collectionVoList = records.stream().map(collection -> {
            CollectionVo vo = new CollectionVo();
            BeanUtils.copyProperties(collection, vo);
            vo.setGameName(finalGameNameMap.getOrDefault(collection.getGameId(), "N/A"));
            vo.setUserName(finalUserNameMap.getOrDefault(collection.getUserId(), "N/A"));
            return vo;
        }).toList();

        // 构建最终分页结果
        Page<CollectionVo> resultPage = new Page<>(
                selectPage.getCurrent(),
                selectPage.getSize(),
                selectPage.getTotal()
        );
        resultPage.setRecords(collectionVoList);
        return resultPage;
    }

    @Override
    public Result userSelect(Long userId, Long gameId) {
        UserGameCollection collection = Db.lambdaQuery(UserGameCollection.class)
                .eq(UserGameCollection::getUserId, userId)
                .eq(UserGameCollection::getGameId, gameId)
                .one();
        return Result.success(collection);
    }

    @Override
    public Result userAddorDelete(UserGameCollection userGameCollection) {
        Long userId = userGameCollection.getUserId();
        Long gameId = userGameCollection.getGameId();
        UserGameCollection collection = Db.lambdaQuery(UserGameCollection.class)
                .eq(UserGameCollection::getUserId, userId)
                .eq(UserGameCollection::getGameId, gameId)
                .one();
        if (collection == null)
            userGameCollectionMapper.insert(userGameCollection);
        else
            userGameCollectionMapper.deleteById(collection);
        return Result.success();
    }

    @Override
    public Result userSelectById(Long userId) {
        List<Long> gameIds = Db.lambdaQuery(UserGameCollection.class)
                .eq(UserGameCollection::getUserId, userId)
                .list()
                .stream()
                .map(UserGameCollection::getGameId)
                .toList();
        List<Game> games = Db.lambdaQuery(Game.class)
                .in(Game::getGameId, gameIds)
                .list();
        List<GameVo> vos = new ArrayList<>();
        games.forEach(game -> {
            GameVo vo = BeanUtil.copyProperties(game, GameVo.class);
            vos.add(vo);
        });
        return Result.success(vos);
    }
}
